package com.cqggrw.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.cqggrw.dao.AdDaoI;
import com.cqggrw.domain.Ad;
import com.cqggrw.util.DBUtil;
import com.cqggrw.util.Utils;

public class AdDaoImpl implements AdDaoI {

	public List<Ad> get() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Ad ad = null;
		List<Ad> list = new ArrayList<Ad>();
		
		String sql = "SELECT * FROM tbl_ad;";
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				ad = new Ad();
				ad.setId(rs.getInt("id"));
				ad.setPage(rs.getString("page"));
				ad.setPlace(rs.getString("place"));
				ad.setImgName(rs.getString("imgName"));
				ad.setLink(rs.getString("link"));
				list.add(ad);
			}
		} catch (Exception e) {
			Utils.log(e);
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return list;
	}

	public boolean modify(Ad ad) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "update tbl_ad set imgName = ?, link = ? WHERE ID = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setString(1, ad.getImgName());
			ps.setString(2, ad.getLink());
			ps.setInt(3, ad.getId());
			i = ps.executeUpdate();
		} catch (Exception e) {
			Utils.log(e);
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1;
	}

	public Ad get(int id) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Ad ad = null;
		
		String sql = "SELECT * FROM tbl_ad where id = ?;";
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if (rs.next()) {
				ad = new Ad();
				ad.setId(rs.getInt("id"));
				ad.setPage(rs.getString("page"));
				ad.setPlace(rs.getString("place"));
				ad.setImgName(rs.getString("imgName"));
				ad.setLink(rs.getString("link"));
			}
		} catch (Exception e) {
			Utils.log(e);
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return ad;
	}

}
